package com.hontech.pastadebug.service

import activity.MainActivity
import android.app.ActivityManager
import android.app.AlarmManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.util.Log
import app.App
import ext.log

class KeepAliveService : Service(), Runnable, Thread.UncaughtExceptionHandler {

    companion object {

        const val MAIN_PROGRESS_NAME = App.PROCESS
        const val KEEP_ALIVE_NAME = "com.hontech.keep.alive.progress"

        /**
         * 由主进程调用
         * 第一次启动时调用
         * 主进程发生子进程退出时调用
         */
        fun startKeepAlive(context: Context) {
            val i = Intent(context, KeepAliveService::class.java)
            context.startService(i)
        }

        fun keepAliveIsRun(context: Context): Boolean {
            val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            am.runningAppProcesses.forEach {
                if (it.processName == KEEP_ALIVE_NAME) {
                    return true
                }
            }
            return false
        }

        fun mainProcessTimerCallback(context: Context) {

            try {
                val ret = keepAliveIsRun(context)
                log("子进程状态：$ret")
                if (!ret) {
                    startKeepAlive(context)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        /**
         * 子进程发生Java异常时调用
         */
        private fun resetKeepAlive(context: Context) {
            val i = Intent(context, KeepAliveService::class.java)
            val pi = PendingIntent.getService(context, 0, i, 0)
            val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 500, pi)
            android.os.Process.killProcess(android.os.Process.myPid())
        }

        /**
         * 主进程发生异常时
         * 子进程负责重启主进程
         */
        private fun resetMain(context: Context) {
            val i = Intent(context, MainActivity::class.java)
            i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            val pi = PendingIntent.getActivity(context, 0, i, 0)
            val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 500, pi)
        }
    }

    private val mHandler = Handler()

    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        Thread.setDefaultUncaughtExceptionHandler(this)
        Log.d("子进程", "子进程启动")
        mHandler.removeCallbacks(this)
        mHandler.post(this)
    }

    override fun run() {
        val run = mainProcessIsRun()
        Log.d("子进程消息", "主进程运行状态：$run")
        if (!run) {
            Log.d("子进程", "主进程退出 重启主进程")
            resetMain(this)
        }
        mHandler.postDelayed(this, 5000)
    }

    override fun uncaughtException(p0: Thread, p1: Throwable) {
        p1.printStackTrace()
        Log.d("子进程", "子进程的Java异常")
        resetKeepAlive(this)
    }

    private fun mainProcessIsRun(): Boolean {
        val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        am.runningAppProcesses.forEach {
            if (it.processName == MAIN_PROGRESS_NAME) {
                return true
            }
        }
        return false
    }

}
